const ts = require('rollup-plugin-typescript2')
const json = require('@rollup/plugin-json')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const path = require('path')
const del = require('rollup-plugin-delete')
const { target, NODE_ENV } = process.env

const pkgPath = path.resolve(__dirname, 'packages', target)
// const env = NODE_ENV == 'development' ? `.dev` : `.pro`

const {
  buildOptions: { name, formats, sourcemap }
} = require(path.join(pkgPath, 'package.json'))

const targetMap = {
  'esm-bundler': 'es',
  'esm-browser': 'es',
  cjs: 'cjs',
  global: 'iife'
}

module.exports = {
  input: `./packages/${target}/src/index.ts`,
  output: flat(
    formats.map(format => {
      return [
        {
          file: `packages/${target}/dist/${format}.dev.js`,
          format: targetMap[format],
          name: name,
          sourcemap: sourcemap
        },
        {
          file: `packages/${target}/dist/${format}.pro.js`,
          format: targetMap[format],
          name: name,
          sourcemap: sourcemap
        }
      ]
    })
  ),
  plugins: [
    json(),
    ts({ tsconfig: path.resolve(__dirname, 'tsconfig.json') }),
    nodeResolve(),
    del({ targets: `packages/${target}/dist/*` })
  ]
}

function flat(arr) {
  const result = []
  arr.forEach(item => {
    if (Array.isArray(item)) {
      result.push(...flat(item))
    } else {
      result.push(item)
    }
  })
  return result
}
